package net.freebytes.config.refresh.config;

import net.freebytes.config.refresh.util.ConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * 每隔1s读取并更新一次配置文件
 *
 * @author 千里明月
 */
@Component
public class ConfigRefresher {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigRefresher.class);

    @PostConstruct
    void refresh() {
        Thread configRefresh = new Thread(new ConfigRefresh());
        configRefresh.start();
    }

    class ConfigRefresh implements Runnable {
        @Override
        public void run() {
            try {
                Properties properties = new Properties();
                String author;
                String gitee;
                String email;
                String configFilePath = ConfigUtils.getPath();
                if (!StringUtils.hasText(configFilePath)) {
                    return;
                }

                while (true) {
                    FileReader fileReader = new FileReader(configFilePath);
                    BufferedReader bufferedReader = new BufferedReader(fileReader);
                    properties.load(bufferedReader);

                    author = properties.getProperty("author", ConfigConstants.getAuthor());
                    gitee = properties.getProperty("gitee", ConfigConstants.getGitee());
                    email = properties.getProperty("email", ConfigConstants.getemail());

                    ConfigConstants.setAuthorValue(author);
                    ConfigConstants.setGiteeValue(gitee);
                    ConfigConstants.setEmailValue(email);

                    bufferedReader.close();
                    fileReader.close();
                    TimeUnit.SECONDS.sleep(1);
                }
            } catch (IOException | InterruptedException e) {
                LOGGER.error("读取配置文件异常", e);
            }
        }

    }
}
